import { addGlobalUncaughtErrorHandler, registerMicroApps, start } from 'qiankun'
import { isMobile } from '../utils/mobile-adapter'

// 定义子应用接口
interface MicroApp {
  name: string
  entry: string
  container: string
  activeRule: string
  props?: any
}

// 获取当前设备类型对应的容器ID
const getContainerId = (): string => {
  return isMobile() ? '#mobile-container' : '#container'
}

// 定义要注册的子应用
const apps: MicroApp[] = [
  {
    name: 'administration',

    entry: '//172.20.10.5:8082',


    container: getContainerId(),
    activeRule: '/administration',
    props: {
      mainAppData: {
        currentUser: JSON.parse(localStorage.getItem('user') || 'null'),
        isMobile: isMobile(),
      },
    },
  },
  {
    name: 'organization',

    entry: '//172.20.10.5:6969',

    container: getContainerId(),
    activeRule: '/organization',
    props: {
      mainAppData: {
        currentUser: JSON.parse(localStorage.getItem('user') || 'null'),
        isMobile: isMobile(),
      },
    },
  },
  {
    name: 'finance',

    entry: '//172.20.10.5:7070',

    container: getContainerId(),
    activeRule: '/finance',
    props: {
      mainAppData: {
        currentUser: JSON.parse(localStorage.getItem('user') || 'null'),
        isMobile: isMobile(),
      },
    },
  },
  {
    name: 'process',

    entry: '//172.20.10.5:7071',

    container: getContainerId(),
    activeRule: '/process',
    props: {
      mainAppData: {
        currentUser: JSON.parse(localStorage.getItem('user') || 'null'),
        isMobile: isMobile(),
      },
    },
  },

  {
    name: 'staff',

    entry: '//172.20.10.5:5555',

    container: getContainerId(),
    activeRule: '/staff',
    props: {
      mainAppData: {
        currentUser: JSON.parse(localStorage.getItem('user') || 'null'),
        isMobile: isMobile(),
      },
    },
  },
  {
    name: 'reactApp',

    entry: '//172.20.10.5:8081',

    container: getContainerId(),
    activeRule: '/react',
    props: {
      mainAppData: {
        currentUser: JSON.parse(localStorage.getItem('user') || 'null'),
        isMobile: isMobile(),
      },
    },
  },
]

// 注册微应用
registerMicroApps(apps, {
  beforeLoad: (app) => {
    console.log('[MainApp] 加载子应用前:', app.name)
    return Promise.resolve()
  },
  beforeMount: (app) => {
    console.log('[MainApp] 挂载子应用前:', app.name)
    return Promise.resolve()
  },
  afterMount: (app) => {
    console.log('[MainApp] 挂载子应用成功:', app.name)
    return Promise.resolve()
  },
})

// 全局错误处理
addGlobalUncaughtErrorHandler((event: any) => {
  // 处理 qiankun 的错误事件
  if (event?.type === 'unhandledrejection' && event?.reason?.isAxiosError) {
    console.warn('子应用网络请求错误:', event.reason.message)
    return
  }

  if (typeof event?.msg === 'string') {
    if (event.msg.includes('died in statuS LOADING SOURCE CODE')) {
      console.error('子应用加载失败，请检查子应用服务是否启动')
    } else if (event.msg.includes('Failed to fetch') || event.msg.includes('NetworkError')) {
      console.error('子应用资源加载失败，网络问题或资源不存在')
    }
  }
})

// 使用requestIdleCallback进行预加载
const prefetchApps = () => {
  // 判断浏览器是否支持requestIdleCallback
  const requestIdleCallback =
    (window as any).requestIdleCallback || ((cb: Function) => setTimeout(cb, 1))

  // 获取所有子应用的entry
  const appEntries = apps.map((app) => app.entry)

  // 在浏览器空闲时预加载
  requestIdleCallback(() => {
    console.log('[MainApp] 开始预加载子应用资源')

    // 预加载所有子应用的入口资源
    appEntries.forEach((entry) => {
      // 创建一个link标签预加载入口HTML
      const link = document.createElement('link')
      link.rel = 'prefetch'
      link.href = entry
      link.as = 'document'
      document.head.appendChild(link)
      console.log(`[MainApp] 预加载子应用: ${entry}`)
    })
  })
}

// 启动函数
export default function startQiankun() {
  // 如果在登录页，不启动乾坤
  if (window.location.pathname.includes('/login')) {
    console.log('当前在登录页，不启动乾坤')
    return
  }

  // 检查容器并启动
  function checkAndStart() {
    const containerSelector = isMobile() ? '#mobile-container' : '#container'
    const container = document.querySelector(containerSelector)

    if (!container) {
      console.log(`容器不存在 (${containerSelector})，稍后重试`)
      setTimeout(checkAndStart, 100)
      return
    }

    console.log(`启动 qiankun, ${isMobile() ? '移动端' : '桌面端'}容器已准备好:`, container)

    // 优化： 使用qiankun的start方法启动乾坤
    start({
      prefetch: false, // 预加载所有子应用
      sandbox: {
        experimentalStyleIsolation: true, // 实验性样式隔离
        strictStyleIsolation: false, // 严格样式隔离会导致一些问题
      },
      singular: true, // 一次只允许一个子应用
    })

    // 启动自定义预加载
    prefetchApps()
  }

  checkAndStart()

  // 监听窗口大小变化，在移动端和桌面端切换时重新加载
  let lastIsMobileState = isMobile()
  window.addEventListener('resize', () => {
    const currentIsMobile = isMobile()
    // 如果设备类型发生变化，刷新页面以重新加载子应用
    if (currentIsMobile !== lastIsMobileState) {
      lastIsMobileState = currentIsMobile
      window.location.reload()
    }
  })
}
